package com.garbagecan.cachestudy.ehcache;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

import java.net.URL;
import java.util.List;

public class DistributionCache {

	private CacheManager cacheManager;

	public static void main(String[]args) throws Exception {
		DistributionCache dc = new DistributionCache();
		if (args.length != 1) {
			if (args[0].equals("dc1")) {
				dc.startDC1();
			} else {
				dc.startDC2();
			}
		}
	}

	private void startDC1() throws Exception {
		URL url = DistributionCache.class.getResource("/ehcache-dc1.xml");
		cacheManager = new CacheManager(url);

		for (int i = 0; i < 10000; i++) {
			Object key = "key__" + i;
			Object value = "value__" + i;
			writeToCache(key, value);
		}

		for (int i = 0; i < 100; i++) {
			String msg = "dc1----------------------------------\n";
			Object key = "key_" + i;
			Object value = "value_" + i;
			writeToCache(key, value);
			msg += "put " + key + "=" + value + "\n";
			value = readFromCache(key);
			msg += "get " + key + "=" + value + "\n";

//			key = "key_" + 0;
//			value = readFromCache(key);
//			msg += "get " + key + "=" + value + "\n";

			print(msg);
			Thread.sleep(5000);
		}
	}

	private void startDC2() throws Exception {
		URL url = DistributionCache.class.getResource("/ehcache-dc2.xml");
		cacheManager = new CacheManager(url);
		while(true) {
			String msg = "dc2----------------------------------\n";
			Object value = readFromCache();
			msg += value;
			print(msg);
			Thread.sleep(5000);
		}
	}

	private void writeToCache(Object key, Object value) {
		Cache cache = cacheManager.getCache("mycache");
		cache.put(new Element(key, value));
	}

	private Object readFromCache(Object key) {
		Cache cache = cacheManager.getCache("mycache");
		Object value = cache.get(key).getObjectValue();
		return value;
	}

	private Object readFromCache() {
		String msg = "";
		Cache cache = cacheManager.getCache("mycache");
		List<?> keys = cache.getKeys();
		msg += "keys size: " + keys.size() + "\n";
		for (int i = 0; i < keys.size(); i++) {
			Object key = keys.get(i);
			Object value = null;
			if (cache.get(key) != null) {
				value = cache.get(key).getObjectValue();
			}
			//msg += "get " + key + "=" + value + "\n";
		}
		return msg;
	}

	private synchronized void print(String msg) {
		System.out.println(msg);
	}
}
